#include "screencap/videocodec.h"
#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QImage>
#include <QScreen>
#include <QGuiApplication>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 初始化 Qt 应用程序
    QGuiApplication app(argc, argv);

    // 创建视频编码器对象
    VideoCodec videoCodec;

    // 创建 TCP 服务器
    QTcpServer server;
    if (!server.listen(QHostAddress::Any, 2234))
    {
        qWarning() << "Failed to start TCP server!";
        return 1;
    }
    qDebug() << "TCP server started, listening on port" << server.serverPort();

    // 等待客户端连接
    QTcpSocket *clientSocket = nullptr;
    QObject::connect(&server, &QTcpServer::newConnection, [&]()
                     {
        clientSocket = server.nextPendingConnection();
        qDebug() << "New client connected!"; });

    // 开始录制屏幕并编码为 H.264 格式
    QScreen *screen = QGuiApplication::primaryScreen();
    const QRect screenGeometry = screen->geometry();

    // 打开编码器并设置参数
    if (!videoCodec.open(nullptr, QPoint(20, 1), "output.h264"))
    {
        qWarning() << "Failed to open video codec!";
        return 1;
    }

    // 循环捕获屏幕图像并编码输出
    while (clientSocket && clientSocket->state() == QTcpSocket::ConnectedState)
    {
        QImage screenImage = screen->grabWindow(0, screenGeometry.x(), screenGeometry.y(),
                                                screenGeometry.width(), screenGeometry.height())
                                 .toImage();

        // 在这里对图像进行处理，比如转换格式等

        // 编码图像并写入输出
        videoCodec.write(QGuiApplication::primaryScreen()->grabWindow(0).toImage());

        // 将编码后的视频数据通过 TCP Socket 发送给客户端
        QByteArray encodedData = videoCodec.getEncodedData();
        if (!encodedData.isEmpty() && clientSocket)
        {
            clientSocket->write(encodedData);
        }

        // 延时一段时间，控制帧率
        QThread::msleep(50);
    }

    // 关闭编码器和 TCP Socket
    videoCodec.close();
    if (clientSocket)
    {
        clientSocket->close();
        clientSocket->deleteLater();
    }

    return a.exec();
}
